package com.wlsk.license.service.setting;

import com.wlsk.license.common.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.FileInputStream;

@Slf4j
@Service
public class LoadInitSettingService implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @PostConstruct
    public void initProperties() throws Exception {
        String active = context.getEnvironment().getActiveProfiles()[0];
        if ("dev".equals(active) || "test".equals(active)) {
            // 本地环境(IDEA)加载配置文件(resources目录下setting.properties)
            PropertiesUtils.initProperties(this.getClass().getResourceAsStream("/setting-dev.properties"));
        } else {
            // 测试环境、正式环境 加载配置文件(JAR文件同目录conf/setting-dev.properties)
            // 外置配置文件方便修改-定时任务定时修改-频率10分钟-xxljob
            String path = ResourceUtils.getURL("classpath:").getPath();
            File rootFile = new File(path);
            if (!rootFile.exists()) {
                rootFile = new File("");
            }
            // rootFile.getAbsolutePath() 返回的是jar包所在目录
            String settingFilePath = rootFile.getAbsolutePath();
            log.info("加载系统设置文件：{}/conf/setting.properties", settingFilePath);
            PropertiesUtils.initProperties(new FileInputStream(new File(settingFilePath, "conf/setting.properties")));
        }
    }

    @PreDestroy
    public void destroy() {
        log.info("数据初始化完成!");
    }
}